package com.ophiux.wechat.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ophiux.wechat.db.MchAppModel;
import com.ophiux.wechat.db.Mch_App_Map;
import com.ophiux.wechat.model.CM_UnifiedOrderRequest;
import com.ophiux.wechat.model.PayJsModel;
import com.ophiux.wechat.model.UnifiedOrderResponse;
import com.ophiux.wechat.utils.CommonUtil;
import com.ophiux.wechat.utils.StringUtil;
import com.ophiux.wechat.utils.WeChatPayUtil;
import com.servlet.WeChatPay;
import com.utils.PayUtils;

/**
 * 20170628 陈辉 新增
 * 通过固定openID进行微信支付，跳过微信授权
 * @author chenh
 *
 */
public class OpenIDPayServlet extends HttpServlet {

	private static Logger logger =LoggerFactory.getLogger(OpenIDPayServlet.class);
	/**
	 * 文件名称: WeChatPay
	 * 内容摘要: 微信支付普通商户授权发起回调地址，在此获取code进行微信用户信息获取（openID），
	 *        然后结合openId发起预支付下单处理生成支付订单，然后调用支付页面，发起支付
	 * 创 建 人: 陈辉
	 * 创建日期:2016-11-14
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		/**
		 * 授权发起页面传来的固定参数
		 * wechatpay.ophiux.com/OphiuxWeChatPayPlatformbuild/OpenIDPayServlet?userId=-1&orderNo=35436646575&money=1&subMchid=1453527302&notifyUrl=&backurl=
		 */
		logger.info("-----------------进入授权回调，开始获取openid-----------------------");
		String userId = request.getParameter("userId");
		String orderNo = request.getParameter("orderNo"); 	
		String money = request.getParameter("money");
	//	String code = request.getParameter("code");
		String subMchid = request.getParameter("subMchid");
		String notifyUrl = request.getParameter("notifyUrl");
		String backurl = request.getParameter("backurl");
		
		/**
		 * 获取openId
		 * appid和appsecret,api_key全部通过subMchid商户号获取
		 */
		 /**
		  * 商户信息,根据MchId获取
		  */
		 MchAppModel mchModel = Mch_App_Map.getMchAppModelByMchId(subMchid);
		 
		 String appid = null;
	     String appsecret = null;
	     String api_key = null;
	     /**
	      * 商户信息存在
	      */
	     if(mchModel != null){
			 appid = mchModel.getAppid();
			 appsecret = mchModel.getAppsecret();
			 api_key = mchModel.getApi_key();
		 }
		//测试:何海龙在“e立达”的openid
		String openId = "oa3s41iq47I3lI5_3_aYntcPz_QU";
				//WeChatPayUtil.Oauth(appid, appsecret, code);
		
		/**
		 * 生成预支付下单请求实体
		 */
		 CM_UnifiedOrderRequest cm_unifiedorder_request = new CM_UnifiedOrderRequest();
		 cm_unifiedorder_request.setAppid(appid);
		 cm_unifiedorder_request.setMch_id(subMchid);
		 cm_unifiedorder_request.setNonce_str(CommonUtil.getNonceStr());
		 //预约挂号/门诊支付
		 cm_unifiedorder_request.setBody("ophiux");
		 cm_unifiedorder_request.setAttach("");
		 cm_unifiedorder_request.setOut_trade_no(orderNo);
		 cm_unifiedorder_request.setTotal_fee(PayUtils.getMoney(money));
		 cm_unifiedorder_request.setSpbill_create_ip(request.getRemoteAddr());
		 cm_unifiedorder_request.setNotify_url(notifyUrl);
		 cm_unifiedorder_request.setTrade_type("JSAPI");
		 cm_unifiedorder_request.setOpenid(openId);
		/**
		 * 调用微信普通商户统一下单
		 */
		 UnifiedOrderResponse unifiedOrder = WeChatPayUtil.UnifiedOrder(cm_unifiedorder_request,api_key);
		 /**
		  * 生成调起JS微信支付需要的参数
		  */
		 PayJsModel payJsParam = null;
		 if(unifiedOrder.getError_code() == "200"){
			 //统一下单成功
			 payJsParam = WeChatPayUtil.toPayJsParam(appid, unifiedOrder.getPrepay_id(), api_key);
		 }else{
			 response.getWriter().write("支付下单出错:"+unifiedOrder.getError_msg());
		 }
		 
		logger.info("-----------------普通商户：唤起支付参数-----------------------");
		logger.info("appid="+payJsParam.getAppId()+"&timeStamp="+payJsParam.getTimeStamp()+
				"&nonceStr="+payJsParam.getNonceStr()+"&package="+payJsParam.getPackages()+
				"&sign="+payJsParam.getPaySign()+"&orderNo="+orderNo+"&backurl="+backurl);
		logger.info("------------------普通商户：唤起支付支付参数----------------------");

		StringBuffer toPayUrl = new StringBuffer();
		toPayUrl = toPayUrl.append("/OphiuxWeChatPayPlatformbuild/pay_temp.jsp").append("?")
				.append("appid=").append(payJsParam.getAppId())
				.append("&timeStamp=").append(payJsParam.getTimeStamp())
				.append("&nonceStr=").append(payJsParam.getNonceStr())
				.append("&package=").append(payJsParam.getPackages())
				.append("&sign=").append(payJsParam.getPaySign())
				.append("&orderNo=").append(orderNo)
				.append("&backurl=").append(backurl);
		
		logger.info("支付唤起地址："+toPayUrl.toString());
		//重定向，启动支付jsp
		response.sendRedirect(toPayUrl.toString());

	}
	

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
}
